package com.ccsoft.leetcode.service;

import com.sun.xml.internal.fastinfoset.util.CharArray;
import org.springframework.stereotype.Service;
import sun.util.resources.cldr.ar.CalendarData_ar_YE;

/**
 * 67. 二进制求和
 * 返回二进制字符串的和 - 二进制表示的和的字符串
 */
@Service
public class AddBinary {
    public String addBinary(String a, String b) {
        // 采用二进制相加的方法
        int lena = a.length();
        int lenb = b.length();
        int diff = Math.abs(lena - lenb);
        if( lena > lenb ){
            for(int i=0;i<diff;i++){
                b = "0" + b;
            }
        }else {
            for(int i=0;i<diff;i++){
                a = "0" + a;
            }
        }

        int len = a.length();
        int carry = 0;
        int current = 0;
        String[] result = new String[len];
        for(int i=len-1;i>=0;i--){
            int addResult = Integer.parseInt(a.substring(i,i+1)) + Integer.parseInt(b.substring(i,i+1)) + carry;
            switch(addResult){
                case 2:
                    carry = 1;
                    current = 0;
                    break;
                case 3:
                    carry = 1;
                    current = 1;
                    break;
                default:
                    current = addResult;
                    carry = 0;
            }
            result[i] = String.valueOf(current);
        }

        String ret = "";
        for(int i=0;i<result.length;i++){
            if( result[i] != "0" ) ret = ret + result[i];
        }
        ret = carry == 1 ? "1" + ret : ret;
        return ret;

        // 下面采用数据类型转换的方式计算，如果二进制字符串超过 Integer 的范围则会报异常
//        String aString = Integer.valueOf(a,2).toString();
//        String bString = Integer.valueOf(b,2).toString();
//        Integer result = Integer.parseInt(aString) + Integer.parseInt(bString);
//
//        return Integer.toBinaryString(result);
    }

    public static void main(String[] args) {
        System.out.println(Integer.toBinaryString(2));
    }
}
